require 'skit/health/version'

module Skit
  module Health
    def self.run_server(port_or_socket, &block)
      unless block_given?
        puts 'Health server not running, no block given!'
        return
      end

      require_em_synchrony!
      require 'skit/health/server'

      EventMachine.synchrony do
        server = Skit::Health::Server.new(port_or_socket, &block)
        server.start

        %w(INT TERM QUIT).each do |sig|
          Signal.trap(sig) do
            debug("Caught signal: #{sig}. Stopping health check server...")
            server.stop
          end
        end

        Signal.trap('USR2') do
          Skit::Health.run_check(block)
        end
      end
    end

    def self.run_check(block)
      begin
        block.call.to_s
      rescue => e
        "Error! #{e.class}: #{e}"
      end
    end

    def self.path_to_socket(root, prefix = nil)
      dir = File.join(root, 'tmp', 'sockets')
      socket_name = "#{prefix}health_check.sock"

      return File.join(dir, socket_name) if Dir.exist?(dir)

      File.join(root, socket_name)
    end

    def self.enable_debug
      ENV['SKIT_HEALTH_DEBUG'] = '1'
    end

    def self.debug(message)
      puts "[skit-health]: #{message}" if debug_enabled?
    end

    def self.debug_enabled?
      ENV['SKIT_HEALTH_DEBUG'] || ENV['SKIT_DEBUG']
    end

    def self.require_em_synchrony!
      begin
        require 'em-synchrony'
      rescue LoadError
        $stderr.puts "You need em-synchrony ~> 1.0 gem " +
          "to run Skit::Health::Server. " +
          "Please add it to Gemfile and run 'bundle install'."
        exit 1
      end
    end
  end
end
